package io.p2p.stream.turn.handler.udp;

import com.alibaba.fastjson.JSONObject;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.DatagramPacket;
import io.p2p.stream.turn.handler.TurnBaseHandler;
import io.p2p.stream.turn.session.ActiveNodeSessionManager;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;

/**
 * 客户端心跳协议类
 */
@Slf4j
public class ClientHeartbeatHandler implements TurnBaseHandler {
    public static final String commandType = "clientHeartbeat";

    @Override
    public void process(ChannelHandlerContext ctx,InetSocketAddress remoteAddress,String buffer) {

    }

    @Override
    public void process(ChannelHandlerContext ctx, InetSocketAddress remoteAddress,JSONObject buffer) {
        String remoteAddrStr = remoteAddress.toString();

        String loginName = String.valueOf(buffer.get("name"));

        String[] remoteAddr = remoteAddrStr.split(":");

        String clientIp = remoteAddr[0].replace("/","");
        int clientPort = Integer.parseInt(remoteAddr[1]);

        //刷新节点
        ActiveNodeSessionManager.getInstance().flush(loginName,clientIp,clientPort);

        //log.info("Received client heartbeat data at IP: {},Port: {},Name: {}.",clientIp,clientPort,loginName);

        //发送心跳应答指令给客户端
        JSONObject ack = new JSONObject();
        ack.put("type","turnHeartbeatAck");

        String msg = String.format("Client at IP: %s,Port: %s,Name: %s is active.",clientIp,clientPort,loginName);
        ack.put("msg",msg);

        ctx.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(
                ack.toJSONString(), StandardCharsets.UTF_8), new InetSocketAddress(clientIp,clientPort)));
    }

    @Override
    public void process(ChannelHandlerContext ctx,InetSocketAddress remoteAddress,Byte[] buffer) {

    }
}
